# pages/login_page.py
import os
from common.base_page import BasePage
from common.config import Config
from common.ocr_util import ocr_from_file
from pages.user_info import UserPage


class LoginPage(BasePage):
    """登录页面"""
    # 定位方式
    UserName = "#username"
    Password = "#password"
    Verify_Code = "#verify_code"
    Verify_Code_Img = "#verify_code_img"
    Login_Btn = ".J-login-submit"
    Wechat_Login_Btn = ".judgp co_wechat"
    QQ_Login_Btn = ".judgp co_qq"
    Register_Btn = ".judgp co_register"
    Message_Info = ".layui-layer-padding"

    def __init__(self, page):
        super().__init__(page)
        self.page = page

    def _input_username(self, name):  # 输入用户名
        self.fill(self.UserName, name)

    def _input_password(self, pwd):  # 输入密码
        self.fill(self.Password, pwd)

    def _save_verify_img(self):  # 保存验证码图片
        self.screenshot_element(self.Verify_Code_Img, "verify_code.png")

    def _get_verify_code(self):  # 获取验证码
        self._save_verify_img()
        verify_code = ocr_from_file(Config.APP_PATH + os.sep + "verify_img" + os.sep + "verify_code.png")
        return verify_code

    def _input_verify_code(self, verify_code=None):
        if verify_code:
            self.fill(self.Verify_Code, verify_code)
        else:
            self.fill(self.Verify_Code, self._get_verify_code())

    def _click_login_btn(self):
        self.click(self.Login_Btn)

    def _click_verify_code(self):
        self.click(self.Verify_Code_Img)

    def _click_wechat_login_btn(self):
        self.click(self.Wechat_Login_Btn)

    def _click_qq_login_btn(self):
        self.click(self.QQ_Login_Btn)

    def _click_register_btn(self):
        self.click(self.Register_Btn)

    def _get_message_info(self):
        return self.get_text(self.Message_Info)

    def login(self, name, pwd, verify_code=None):
        """
        :param name:用户名
        :param pwd: 密码
        :param verify_code:验证码
        :return:
        """
        # 输入用户名
        self._input_username(name)
        # 输入密码
        self._input_password(pwd)
        # 输入验证码
        self._input_verify_code(verify_code)
        # 点击登录
        self._click_login_btn()
        return UserPage(self.page)

    def reset_verify_code(self):
        # 重置验证码
        self._click_verify_code()

    def wechat_login(self):
        # 打开微信登录
        self._click_wechat_login_btn()

    def qq_login(self):
        # 打开qq登录
        self._click_qq_login_btn()

    def register(self):
        # 打开注册
        self._click_register_btn()

    def get_message_info(self):
        # 获取信息
        return self._get_message_info()
